"""
用户账户相关功能： 注册、短信、登录、注销
"""
import uuid
import datetime
from io import BytesIO
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.views import View
from django.db.models import Q
from django_redis import get_redis_connection
from web import models
from web.forms.account import RegisterModelForm, LoginModelForm, SendSmsForm, UserLoginModelForm
from scripts.img import check_code


def root(request):
    return redirect('index')


def index(request):
    return render(request, 'index.html')


def send_code(request):
    form = SendSmsForm(request, data=request.GET)
    phone = request.GET.get('phone')
    valid = form.is_valid()

    if valid:
        conn = get_redis_connection()
        value = bytes.decode(conn.get(phone))
        result = {
            'status': True,
            'code': value,
        }
        return JsonResponse(result)
    result = {
        'status': False,
        'error': form.errors
    }
    return JsonResponse(result)


def img_code(request):
    img, code = check_code()

    # 将图片写到内存中
    stream = BytesIO()
    img.save(stream, 'png')
    request.session['image_code'] = code
    request.session.set_expiry(60)

    return HttpResponse(stream.getvalue())


def register(request):
    form = RegisterModelForm()
    if request.method == 'GET':
        return render(request, 'register.html', {'form': form, 'title': '注 册'})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()

        # 创建交易记录
        policy_object = models.PriceStrategy.objects.filter(category=1, title="个人免费版").first()

        models.Transaction.objects.create(
            status=2,   # 已支付
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


class Login(View):

    def get(self, request):
        form = LoginModelForm()
        return render(request, 'register.html', {'form': form, 'title': '登 录'})

    def post(self, request):
        form = LoginModelForm(data=request.POST)
        if form.is_valid():
            phone = form.cleaned_data['phone']

            user_object = models.UserInfo.objects.filter(phone=phone).first()
            request.session['user_id'] = user_object.id
            request.session['username'] = user_object.username
            request.session.set_expiry(60 * 60 * 72)

            return JsonResponse({'status': True})
        return JsonResponse({'status': False, 'error': form.errors})


def user_login(request):
    if request.method == 'GET':
        form = UserLoginModelForm(request)
        return render(request, 'user_login.html', {'form': form})

    form = UserLoginModelForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(phone=password)).filter(
            password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session['username'] = user_object.username
            request.session.set_expiry(60 * 60 * 24)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'user_login.html', {'form': form})


def logout(request):
    request.session.flush()
    return redirect('/index/')
